package top.tangyh.lamp.care.mqtt.send;

import org.eclipse.paho.mqttv5.client.IMqttToken;
import org.eclipse.paho.mqttv5.client.MqttAsyncClient;
import org.eclipse.paho.mqttv5.client.MqttConnectionOptions;
import org.eclipse.paho.mqttv5.client.persist.MemoryPersistence;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;

/**
 * @author: zqb
 * @date: 2024/9/13 09:36
 */

public class SendMqtt {


//    private static final String MQTT_BROKER = "tcp://192.168.204.189:1883"; // MQTT服务器地址
//    private static final String clientId = "mqtt5Send001";
//    private static final String USERNAME = "david_mqtt"; // 用户名
//    private static final String PASSWORD = "668877"; //  密码

    public static void sendToMQTT(String content, String topic,String MQTT_BROKER,
                                  String clientId,String USERNAME,String PASSWORD) {
        MemoryPersistence persistence = new MemoryPersistence();
        MqttAsyncClient sampleClient = null;
        try {
            sampleClient = new MqttAsyncClient(MQTT_BROKER, clientId, persistence);
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }

        int qos = 1;

        try {
            MqttConnectionOptions connOpts = new MqttConnectionOptions();
            connOpts.setUserName(USERNAME);
            connOpts.setPassword(PASSWORD.getBytes());
            connOpts.setCleanStart(false);

            System.out.println("Connecting to broker: " + MQTT_BROKER);
            IMqttToken token = sampleClient.connect(connOpts);
            token.waitForCompletion();
            System.out.println("Connected");
            System.out.println("Publishing message to topic " + topic + ": " + content);
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(qos);
            token = sampleClient.publish(topic, message);
            token.waitForCompletion();
        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }
}
